package dockyin.action.pattern.iterator;

public class MyIterator implements Iterator {

    private MyCollection collection;

    private int position = -1;

    public MyIterator(MyCollection collection) {
        this.collection = collection;
    }

    @Override
    public Object previous() {
        try {
            return collection.get(--position);
        } catch (ArrayIndexOutOfBoundsException e) {
            position = 0;
            System.out.println("No previous element any more. null will be returned.");
            return null;
        }
    }

    @Override
    public Object next() {
        try {
            return collection.get(++position);
        } catch (ArrayIndexOutOfBoundsException e) {
            position = collection.size();
            System.out.println("No next element any more. null will be returned.");
            return null;
        }
    }

    @Override
    public boolean hasNext() {
        return position < (collection.size() - 1);
    }

    @Override
    public Object first() {
        position = 0;
        return collection.get(position);
    }
}
